package gui;

import java.util.List;

import model.SparePart;

public class Search {

	/**
	 * Searches for a SparePart according to the requirement uniqueID.
	 * 
	 * @param list -
	 *            List of SpareParts.
	 * @param target -
	 *            UniqueID of the target SparePart. Requirement: the long should
	 *            be 7 digits.
	 * @return to the SparePart which is fits to the target.
	 * 
	 * @author Csaba Tarkanyi
	 */
	public SparePart binarySearchByNumber(List<SparePart> list, long target) {
		// Exception if the target is not fits to the requirements.
		if (Long.toString(target).length() != 7) {
			throw new RuntimeException("The 'target is not 7 digits'! It is "
					+ Long.toString(target).length() + " digits long.");
		}
		boolean found = false;
		int left = 0;// Left position in the searching area.
		int right = list.size() - 1;// Right position in the searching area.
		SparePart sparePart = null;

		while (!found && left <= right) {
			// get SparePart in the middle.
			int middle = (left + right) / 2;// Middle position in the searching
			// area.
			sparePart = list.get(middle);
			// Calculates the different.
			long comp = sparePart.getUniqueID() - target;

			if (comp == 0) // The ID is the same as target.
				found = true;
			else if (comp > 0) // The ID is after target.
				right = middle - 1;
			else
				// The ID is before target.
				left = middle + 1;
		}
		// If there is target, returns to that.
		if (found)
			return sparePart;
		else
			return null;
	}
}